package com.tianji.remark.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.domain.dto.LikedTimesDTO;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.StringUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.constans.RedisConstans;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.tianji.common.constants.MqConstants.Exchange.LIKE_RECORD_EXCHANGE;
import static com.tianji.common.constants.MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author huanghui
 * @since 2023-07-27
 */
@Service
@Slf4j
@RequiredArgsConstructor
public   class LikedRecordServiceRedisImpl extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    private final RabbitMqHelper mqHelper;

    private final StringRedisTemplate redisTemplate;


    @Override
    public void addLikeRecord(LikeRecordFormDTO recordDTO) {
        //1.recordDTO,判断是执行点赞还是取消点赞
        Boolean success = recordDTO.getLiked() ? like(recordDTO):unLike(recordDTO);
        //2.判断是否执行成功，如果失败，则直接结束
        if (!success){
            return;
        }
        //3.如果执行成功，统计点赞数量
        //3.1获取Key
        String key=RedisConstans.LIKES_BIZ_KEY_PREFIX+recordDTO.getBizId();

        Long likeTimes = redisTemplate.opsForSet().size(key);
        if (likeTimes == null) {
            return;
        }
        //4.缓存点总数到redis
        String k = RedisConstans.LIKES_TIMES_KEY_PREFIX + recordDTO.getBizType();
        redisTemplate.opsForZSet().add(k,recordDTO.getBizId().toString(),likeTimes);

    }

    @Override
    public Set<Long> isBizLiked(List<Long> bizIds) {
        //1.查询登录用户id
        Long userId = UserContext.getUser();
        //2.查询点赞状态
        /*
        封装到管道一起执行
         */
        List<Object> objects = redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection src = (StringRedisConnection) connection;
            for (Long bizId : bizIds) {
                String key = RedisConstans.LIKES_BIZ_KEY_PREFIX + bizId;
                src.sIsMember(key, userId.toString());
            }
            return null;
        });

        //3.返回结果
        Set<Long> set = new HashSet<>();
        for (int i = 0; i < objects.size(); i++) {
            Boolean o = (Boolean) objects.get(i);
            if (o) {
                set.add(bizIds.get(i));
            }
        }
        /*Set<Long> set = IntStream.range(0, objects.size())
                .filter(i -> (Boolean) objects.get(i))
                .mapToObj(bizIds::get)
                .collect(Collectors.toSet());*/
        return set;
    }

    @Override
    public void readLikedTimesAndSendMessage(String bizType, int maxBizSize) {
        //1.读取并移除Redis中缓存的点赞总数
        //1.1获取key
        String key=RedisConstans.LIKES_BIZ_KEY_PREFIX+bizType;
        //2.数据转换
        Set<ZSetOperations.TypedTuple<String>> tuples = redisTemplate.opsForZSet().popMin(key, maxBizSize);
        if (CollUtils.isEmpty(tuples)) {
            return ;
        }
        List<LikedTimesDTO> list = new ArrayList<>(tuples.size());
        if (CollUtils.isEmpty(list)) {
            return ;
        }
        for (ZSetOperations.TypedTuple<String> tuple : tuples) {
            Double likedTimes = tuple.getScore();
            String bizId = tuple.getValue();
            if (likedTimes==null || bizId==null) {
                continue;
            }
            list.add(LikedTimesDTO.of(Long.valueOf(bizId),likedTimes.intValue()));
        }
        //3.发送MQ消息
        mqHelper.send(
                LIKE_RECORD_EXCHANGE,
                StringUtils.format(LIKED_TIMES_KEY_TEMPLATE,bizType),
                list
        );
    }


    private Boolean unLike(LikeRecordFormDTO recordDTO) {
        //1.获取用户Id
        Long userId = UserContext.getUser();
        //2.获取key
        String key=RedisConstans.LIKES_BIZ_KEY_PREFIX+recordDTO.getBizId();
        //3.执行SREM命令
        Long result = redisTemplate.opsForSet().remove(key, userId.toString());
        return result!=null&& result>0;
    }


    private Boolean like(LikeRecordFormDTO recordDTO) {
        //1.获取用户Id
        Long userId = UserContext.getUser();
        //2.获取key
        String key=RedisConstans.LIKES_BIZ_KEY_PREFIX+recordDTO.getBizId();
        //3.执行SADD命令
        Long result = redisTemplate.opsForSet().add(key, userId.toString());
        return result!=null&& result>0;
    }
}
